package com.m7788.screen;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Point;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.load.resource.gif.GifDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.GlideDrawableImageViewTarget;
import com.bumptech.glide.request.target.Target;
import com.entity.StartPicEntity;
import com.entity.StartPicResult;
import com.erp.service.util.JSONHelper;
import com.imagemanager.util.CacheService;
import com.m7788.util.AppUtil;
import com.m7788.util.Constant;
import com.m7788.util.DownFileUtil;
import com.m7788.util.HttpService;
import com.m7788.util.ProgressLoadingHelper;
import com.m7788.view.UmengBaseActivity;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.tencent.stat.StatService;
import com.tool.utils.DataUtil;
import com.tool.utils.LogUtil;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class StartScreen extends UmengBaseActivity {
    LinearLayout llytEmpty, llytSkip;
    TextView tvReload, tvSecond;
    ImageView mIvStartPage, mIvBannerPage;
    private String TAG = "StartScreen";
    private GlideDrawableImageViewTarget mBannerTarget,mStartTarget;
    private int delayTime = 5;


    private Handler toNextPageCountHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    int delay = msg.arg1;
                    if (delay == 0) {
                        mIvBannerPage.setVisibility(View.INVISIBLE);
                        llytSkip.setVisibility(View.INVISIBLE);
                        goNextPage("");
                    } else {
                        Message msg1 = toNextPageCountHandler.obtainMessage(1);
                        msg1.arg1 = delay - 1;
                        toNextPageCountHandler.sendMessageDelayed(msg1, 1000);
                    }
                    break;
                case 2:
                    Bundle data = msg.getData();
                    readToLoadBannerPage(getPicUrl(Constant.KEY_BANNER_PAGE),data.getBoolean("hasLoad"),data.getString("url"));
                    break;
                case 3:
                    int second = msg.arg1;
                    tvSecond.setText(second + "");
                    if (second == 0) {
                        goNextPage("");
                    } else {
                        Message msg1 = toNextPageCountHandler.obtainMessage(3);
                        msg1.arg1 = second - 1;
                        toNextPageCountHandler.sendMessageDelayed(msg1, 1000);
                    }
                    break;
            }
        }
    };

    private int mWindownWidth,mWindowHeight;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.start_screen);
        requesPermission();
        llytEmpty = (LinearLayout) findViewById(R.id.llyt_empty);
        tvReload = (TextView) findViewById(R.id.tv_reload);
        llytSkip = (LinearLayout) findViewById(R.id.llyt_skip);
        tvSecond = (TextView) findViewById(R.id.tv_second);
        mIvStartPage = findViewById(R.id.iv_start_page);
        mIvBannerPage = findViewById(R.id.iv_banner_page);
        getWindowWH();

        llytSkip.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                Log.d("TAG","跳过");
                goNextPage("");
            }
        });
        if (DataUtil.isConnectNet(this)) {
            checkAndSetHttps();
        } else {
            llytEmpty.setVisibility(View.VISIBLE);
            tvReload.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    ProgressLoadingHelper.showLoadingDialog(StartScreen.this);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            ProgressLoadingHelper.dismissLoadingDialog();
                        }
                    }, 100);
                    onCreate(null);
                }
            });
            /*AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("网络已断开，请连接网络")
					.setCancelable(false)
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.cancel();
									StartScreen.this.finish();
								}
							});
			builder.show();*/
        }
    }

    private void requesPermission() {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE).subscribe(new Subscriber<Boolean>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(Boolean aBoolean) {
                if (!aBoolean) {
                    Toast.makeText(StartScreen.this, "您没有授权SD卡权限，请在设置中打开授权", Toast.LENGTH_SHORT).show();
                }
            }
        });
        rxPermissions.request(Manifest.permission.WRITE_SETTINGS).subscribe(new Subscriber<Boolean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(Boolean aBoolean) {
                if (!aBoolean) {
                    Toast.makeText(StartScreen.this, "您没有授权设置系统亮度权限，请在设置中打开授权", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void getWindowWH() {
        Point point = new Point();
        getWindowManager().getDefaultDisplay().getSize(point);
        mWindownWidth = point.x;
        mWindowHeight = point.y - getStatusBarHeight();
    }

    private void setDirectory() {
        String config = AppUtil.getRecord(this, Constant.DIRECTORYCONFIG);
        if (config != null && config.length() > 0) {
            String path[] = config.split(";");
            for (String p : path) {
                if (p.length() > 0) {
                    CacheService.addDcimFolder(p.substring(0, p.length() - 1));
                }
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        StatService.onPause(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        StatService.onResume(this);
    }

    // 获取按钮菜单
    private class FileQueryAsyncTask extends AsyncTask<Object, Object, Object> {
        @Override
        protected void onPostExecute(Object result) {
            if (result != null && result.toString().length() > 0) {
                String json = result.toString();
                json = AppUtil.UnicodeToGB2312(json);

                AppUtil.saveRecord(StartScreen.this, Constant.INDEX_MENU, json);
                // String json="{ret:1,arr:[ {path:'xccc',id:'1033'}" +
                // ",{path:'文件夹2',id:'2230'}" +
                // ",{path:'文件夹3',id:'2231'}" +
                // ",{path:'文件夹4',id:'2232'}" +
                // "]}";
            }
            super.onPostExecute(result);
        }

        @Override
        protected Object doInBackground(Object... params) {
            return HttpService.getInstance(StartScreen.this).qryMenu();

        }
    }

    private class FileQueryAsyncTask1 extends AsyncTask<Object, Object, Object> {
        @Override
        protected void onPostExecute(Object result) {
            if (result != null && result.toString().length() > 0) {
                String json = result.toString();
                json = AppUtil.UnicodeToGB2312(json);

                // AppUtil.saveRecord(StartScreen.this, Constant.URL_TOP_MENU,
                // json);

                try {
                    String title_1 = new JSONObject(json).getString("title_1");
                    String url_1 = new JSONObject(json).getString("url_1");
                    String title_2 = new JSONObject(json).getString("title_2");
                    String url_2 = new JSONObject(json).getString("url_2");

                    AppUtil.saveRecord(StartScreen.this,
                            Constant.INDEX_TITLE_LEFT_TEXT, title_1);
                    AppUtil.saveRecord(StartScreen.this,
                            Constant.INDEX_TITLE_LEFT_URL, url_1);
                    AppUtil.saveRecord(StartScreen.this,
                            Constant.INDEX_TITLE_LEFT_TEXT2, title_2);
                    AppUtil.saveRecord(StartScreen.this,
                            Constant.INDEX_TITLE_LEFT_URL2, url_2);

                    AppUtil.sendMesToActivity(StartScreen.this, 55, "");
                    AppUtil.sendMesToActivity(StartScreen.this, 57, "");

                } catch (JSONException e) {
                    e.printStackTrace();
                }

                // String json="{ret:1,arr:[ {path:'xccc',id:'1033'}" +
                // ",{path:'文件夹2',id:'2230'}" +
                // ",{path:'文件夹3',id:'2231'}" +
                // ",{path:'文件夹4',id:'2232'}" +
                // "]}";
            }
            super.onPostExecute(result);
        }

        @Override
        protected Object doInBackground(Object... params) {
            return HttpService.getInstance(StartScreen.this).get_top_Menu();
        }
    }

    private void checkAndSetHttps() {
//		new Thread(new Runnable() {
//			@Override
//			public void run() {
//				final String result = HttpService.set_https();
//					runOnUiThread(new Runnable() {
//
//						@Override
//						public void run() {
//							JSONObject jsonObject;
//							boolean isHttps = false;
//							try {
//								if(TextUtils.isEmpty(result)){
//									isHttps = false;
//								}else{
//									jsonObject = new JSONObject(result);
//									final String vavue = jsonObject.getString("is_https");
//									if (vavue.equals("0")) {
//										isHttps = false;
//									}else{
//										isHttps = true;
//									}
//								}
//							} catch (JSONException e) {
//								isHttps = false;
//								e.printStackTrace();
//							}finally{
        Constant.setHost(true);
        llytEmpty.setVisibility(View.GONE);
        StatService.trackCustomEvent(StartScreen.this, "onCreate", "");
        LogUtil.LogFlag = false;
        setDirectory();
        FileQueryAsyncTask ft = new FileQueryAsyncTask();
        ft.execute();

        FileQueryAsyncTask1 ft1 = new FileQueryAsyncTask1();
        ft1.execute();

        FileQueryAsyncTask2 ft2 = new FileQueryAsyncTask2();
        ft2.execute();
        // new AliPayUtil(this,this,"测试","0.01","huanghaishuitest").goPay();

        // new WXPayUtil(this,"测试","1","huanghaishuitest").goPay();

        WebView mWebView = (WebView) findViewById(R.id.ss_webview);
        WebSettings webSettings = mWebView.getSettings();
        String ua = webSettings.getUserAgentString();


        SharedPreferences mSharedPreference = PreferenceManager.getDefaultSharedPreferences(StartScreen.this);
        SharedPreferences.Editor editor = mSharedPreference.edit();
        editor.putString(Constant.UA,ua);
        editor.commit();

        final String startPageUrl = mSharedPreference.getString(Constant.KEY_START_PAGE, "");
        boolean hasLoadedStartPage = hasDownLoadedPic(startPageUrl);
        if (mSharedPreference.getString("isFirstUse", "true").equals("true")||!hasLoadedStartPage) {
            Log.d(TAG,"加载默认启动页");
            int pos = getRP_Pos();
            final int drawableId;
            if (pos == 1 || pos == 3) {
                drawableId = R.drawable.welcome2;
            } else {
                drawableId = R.drawable.welcome1;
            }
            mIvStartPage.setImageResource(drawableId);
        } else {
            readToloadStartPage(startPageUrl,true);
        }
        getStartPage();
//							}
//						}
//					});
//			}
//		}).start();
    }

    private void readToloadStartPage(final String url, final boolean hasLoad) {
        String fileName = getFileNameFromUrl(url);
        if(hasLoad){
            mStartTarget = new GlideDrawableImageViewTarget(mIvStartPage);
            SharedPreferences mSharedPreference = PreferenceManager.getDefaultSharedPreferences(StartScreen.this);
            if(!mSharedPreference.getString("isFirstUse", "true").equals("true")){
                File file = new File(Constant.CACHE_PATH+File.separator+fileName);
                Glide.with(this).load(file).diskCacheStrategy(DiskCacheStrategy.NONE).listener(new RequestListener<File, GlideDrawable>() {
                    @Override
                    public boolean onException(Exception e, File file, Target<GlideDrawable> target, boolean b) {
                        Log.d(TAG,"启动页加载异常");
                        goNextPage("");
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GlideDrawable glideDrawable, File file, Target<GlideDrawable> target, boolean b, boolean b1) {
                        return false;
                    }
                }).into(mStartTarget);
            }
        }else{
            Log.d(TAG,"下载启动页");
            DownFileUtil downFileUtil = new DownFileUtil();
            downFileUtil.downFile(this,url,Constant.CACHE_PATH_NAME,fileName);
        }
    }

    private String getFileNameFromUrl(String url){
        if(!TextUtils.isEmpty(url)){
            String[] s = url.split("/");
            if(s.length>0){
                return  s[s.length-1];
            }
        }
        return  "";
    }

    private String getPicUrl(String key) {
        SharedPreferences mSharedPreference = PreferenceManager.getDefaultSharedPreferences(StartScreen.this);
        return mSharedPreference.getString(key, "");
    }

    private void storePicUrls(StartPicResult startPicResult) {
        if (startPicResult != null) {
            SharedPreferences mSharedPreference = PreferenceManager.getDefaultSharedPreferences(StartScreen.this);
            SharedPreferences.Editor editor = mSharedPreference.edit();
            StartPicEntity startPicEntity1 = startPicResult.getStart_page_1();
            StartPicEntity startPicEntity2 = startPicResult.getStart_page_2();
            int rp_pos = getRP_Pos();
            if (startPicEntity1 != null) {
                editor.putString(Constant.KEY_START_320X480, startPicEntity1.getImg_url1());
                editor.putString(Constant.KEY_START_1080X1920, startPicEntity1.getImg_url2());
                editor.putString(Constant.KEY_START_1152X1920, startPicEntity1.getImg_url3());
                switch (rp_pos) {
                    case 1:
                        editor.putString(Constant.KEY_START_PAGE, startPicEntity1.getImg_url1());
                        break;
                    case 2:
                        editor.putString(Constant.KEY_START_PAGE, startPicEntity1.getImg_url2());
                        break;
                    case 3:
                        editor.putString(Constant.KEY_START_PAGE, startPicEntity1.getImg_url3());
                        break;
                }
            }
            if (startPicEntity2 != null) {
                editor.putString(Constant.KEY_BANNER_320X480, startPicEntity2.getImg_url1());
                editor.putString(Constant.KEY_BANNER_1080X1920, startPicEntity2.getImg_url2());
                editor.putString(Constant.KEY_BANNER_1152X1920, startPicEntity2.getImg_url3());
                editor.putInt(Constant.KEY_BANNER_TIME, startPicEntity2.getNext_time());
                switch (rp_pos) {
                    case 1:
                        editor.putString(Constant.KEY_BANNER_PAGE, startPicEntity2.getImg_url1());
                        break;
                    case 2:
                        editor.putString(Constant.KEY_BANNER_PAGE, startPicEntity2.getImg_url2());
                        break;
                    case 3:
                        editor.putString(Constant.KEY_BANNER_PAGE, startPicEntity2.getImg_url3());
                        break;
                }
            }
            editor.commit();
        }
    }

    private void getStartPage() {
        Log.d(TAG,"开启2s检测");
        Message msg = toNextPageCountHandler.obtainMessage(1);
        msg.arg1 = 2;
        msg.sendToTarget();

        Observable.create(new Observable.OnSubscribe<StartPicResult>() {
            @Override
            public void call(Subscriber<? super StartPicResult> subscriber) {
                String result = HttpService.getInstance(StartScreen.this).set_start_page();
                StartPicResult startPicResult = null;
                if (!TextUtils.isEmpty(result)) {
                    startPicResult = JSONHelper.deserialize(StartPicResult.class, result);
                    storePicUrls(startPicResult);
                }
                subscriber.onNext(startPicResult);
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<StartPicResult>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(final StartPicResult s) {
                if (s != null) {
                    if (s.getStart_page_2() != null) {
                        if(hasDownLoadedPic(getPicUrl(Constant.KEY_BANNER_PAGE))){
                            SharedPreferences mSharedPreference = PreferenceManager.getDefaultSharedPreferences(StartScreen.this);
                            if (!mSharedPreference.getString("isFirstUse", "true").equals("true")) {
                                Log.d(TAG,"已下载广告栏，关闭2秒检测");
                                toNextPageCountHandler.removeMessages(1);

                                Message msg = toNextPageCountHandler.obtainMessage();
                                msg.what = 2;
                                Bundle data = new Bundle();
                                data.putString("url",s.getStart_page_2().getUrl());
                                data.putBoolean("hasLoad",true);
                                msg.setData(data);
                                toNextPageCountHandler.sendMessageDelayed(msg,1500);

                                Message msg2 = toNextPageCountHandler.obtainMessage();
                                msg2.what = 1;
                                msg2.arg1 = delayTime;
                                toNextPageCountHandler.sendMessageDelayed(msg2,1500);
                            }
                        }else{
                            readToLoadBannerPage(getPicUrl(Constant.KEY_BANNER_PAGE), false, s.getStart_page_2().getUrl());
                        }
                    }
                    if (s.getStart_page_1() != null) {
                        readToloadStartPage(getPicUrl(Constant.KEY_START_PAGE), hasDownLoadedPic(getPicUrl(Constant.KEY_START_PAGE)));
                    }
                }
            }
        });
    }

    private boolean hasDownLoadedPic(String picUrl) {
        if(!TextUtils.isEmpty(picUrl)){
            String fileName = getFileNameFromUrl(picUrl);
            File file = new File(Constant.CACHE_PATH,fileName);
            return file.exists();
        }else{
            return false;
        }
    }

    private void readToLoadBannerPage(final String url, final boolean hasLoad, final String linkUrl) {
        String fileName = getFileNameFromUrl(url);
        if(hasLoad){
            File file = new File(Constant.CACHE_PATH+File.separator+fileName);
            Log.d(TAG,"开始加载广告");
            if(fileName.contains(".gif")){
                try {
                    Glide.with(this).load(file).asGif().skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.SOURCE).listener(new RequestListener<File, GifDrawable>() {
                        @Override
                        public boolean onException(Exception e, File model, Target<GifDrawable> target, boolean isFirstResource) {
                            Log.d(TAG,"banner异常");
                            goNextPage("");
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(GifDrawable resource, File model, Target<GifDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                            SharedPreferences mSharedPreference = PreferenceManager.getDefaultSharedPreferences(StartScreen.this);
                            Log.d(TAG,"广告栏加载成功，关闭2秒检测");
                            toNextPageCountHandler.removeMessages(1);
                            llytSkip.setVisibility(View.VISIBLE);
                            int time = mSharedPreference.getInt(Constant.KEY_BANNER_TIME, 0);
                            Message msg = toNextPageCountHandler.obtainMessage(3);
                            msg.arg1 = time;
                            msg.sendToTarget();
                            mIvBannerPage.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    Log.d(TAG,"banner广告跳转");
                                    goNextPage(Constant.getURL() + linkUrl);
                                }
                            });
                            return false;
                        }
                    }).into(mIvBannerPage);
                }catch (Exception e){
                    Log.d(TAG,"banner异常");
                    goNextPage("");
                }
            }else{
                mBannerTarget = new GlideDrawableImageViewTarget(mIvBannerPage);
                Glide.with(this).load(file).skipMemoryCache(true).listener(new RequestListener<File, GlideDrawable>() {
                    @Override
                    public boolean onException(Exception e, File model, Target<GlideDrawable> target, boolean isFirstResource) {
                        Log.d(TAG,"banner异常");
                        goNextPage("");
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GlideDrawable resource, File model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                        SharedPreferences mSharedPreference = PreferenceManager.getDefaultSharedPreferences(StartScreen.this);
                        Log.d(TAG,"广告栏加载成功，关闭2秒检测");
                        toNextPageCountHandler.removeMessages(1);
                        llytSkip.setVisibility(View.VISIBLE);
                        int time = mSharedPreference.getInt(Constant.KEY_BANNER_TIME, 0);
                        Message msg = toNextPageCountHandler.obtainMessage(1);
                        msg.arg1 = time;
                        msg.sendToTarget();
                        mIvBannerPage.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                toNextPageCountHandler.removeMessages(1);
                                Log.d(TAG,"banner广告跳转");
                                goNextPage(Constant.getURL() + linkUrl);
                            }
                        });
                        return false;
                    }
                }).into(mBannerTarget);
            }
        }else{
            Log.d(TAG,"开始下载广告");
            DownFileUtil downFileUtil = new DownFileUtil();
            downFileUtil.downFile(this,url,Constant.CACHE_PATH_NAME,fileName);
        }
    }

    private int getRP_Pos() {
        int pos = 2;
        float proportion = (mWindowHeight + 0.0f) / mWindownWidth;
        float dif_proportion_1 = Math.abs(480.0f / 320 - proportion);
        float dif_proportion_2 = Math.abs(1920f / 1080 - proportion);
        float dif_proportion_3 = Math.abs(1920f / 1152 - proportion);
        if (dif_proportion_1 <= dif_proportion_2 && dif_proportion_1 <= dif_proportion_3) {
            pos = 1;
        } else if (dif_proportion_2 <= dif_proportion_1 && dif_proportion_2 <= dif_proportion_3) {
            pos = 2;
        } else if (dif_proportion_3 <= dif_proportion_1 && dif_proportion_3 <= dif_proportion_2) {
            pos = 3;
        }
        return pos;
    }

    private int getStatusBarHeight() {
        int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }
    
    private void goNextPage(String url) {
        Log.d(TAG,"跳转下一页面，关闭2秒检测");
        toNextPageCountHandler.removeMessages(1);
        toNextPageCountHandler.removeMessages(2);
        toNextPageCountHandler.removeMessages(3);
        Intent intent = new Intent(StartScreen.this,
                LoginScreen.class);
        intent.putExtra("url", url);
        startActivity(intent);
        StartScreen.this.finish();
    }

    private class FileQueryAsyncTask2 extends AsyncTask<Object, Object, Object> {
        @Override
        protected void onPostExecute(Object result) {
            if (result != null && result.toString().length() > 0) {
                String json = result.toString();
                json = AppUtil.UnicodeToGB2312(json);

                File file = new File("/mnt/emmc/dcim/");
                if (file.exists()) {
                    if (file.listFiles().length > 0) {
                        for (File temp : file.listFiles()) {
                            if (temp.isDirectory()) {
                                CacheService.addDcimFolder(temp
                                        .getAbsolutePath());
                            }
                        }
                    }
                }

                // 直接传路径,路径必须为绝对路径
                // CacheService.addDcimFolder("/mnt/sdcard/wandoujia/image");
                // CacheService.addDcimFolder("/storage/sdcard0/相机/照片");
                // CacheService.addDcimFolder("/mnt/sdcard/我的照片");
                // CacheService.addDcimFolder("/mnt/sdcard/dcim");

                try {
                    String ret = new JSONObject(json).getString("ret");
                    JSONArray array1 = new JSONObject(json).getJSONArray("arr");
                    if ("0".equals(ret)) {

                    } else if ("1".equals(ret)) {
                        for (int i = 0; i < array1.length(); i++) {
                            JSONObject obj = (JSONObject) array1.get(i);
                            String path = obj.getString("path");
                            CacheService.addDcimFolder(path);
                        }

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
            super.onPostExecute(result);
        }

        @Override
        protected Object doInBackground(Object... params) {
            return HttpService.getInstance(StartScreen.this).get_AlbumScreen();
        }
    }

    @Override
    protected void onDestroy() {
        Log.d(TAG,"回收资源");
        toNextPageCountHandler.removeMessages(1);
        toNextPageCountHandler.removeMessages(2);
        toNextPageCountHandler.removeMessages(3);
        if(mStartTarget!=null){
            Glide.clear(mStartTarget);
        }
        if(mBannerTarget!=null){
            Glide.clear(mBannerTarget);
        }else{
            Glide.clear(mIvBannerPage);
        }
        ViewGroup rootview = ((ViewGroup)mIvStartPage.getParent());
        Glide.clear(mIvBannerPage);
        rootview.removeView(mIvStartPage);
        rootview.removeView(mIvBannerPage);
        mIvBannerPage = null;
        mIvStartPage = null;
        toNextPageCountHandler.removeCallbacksAndMessages(null);
        System.gc();
        super.onDestroy();
    }
}